extends KinematicBody2D

class_name Unit

enum TYPE {
	COMMAND = 0,
	AA, 
	INFANTRY, 
	ARTILLERY,
	ARMORED,
	MORTAR,
	RECO,
	TRANSPORT
	}

var type_string : Array = [
	"Command",
	"AA",
	"Infantry",
	"Artillery",
	"Armored",
	"Mortar",
	"Reco",
	"Transport"
]

export (TYPE) var type
export (String) var unit_name
export (bool) var can_rotate = true
export (bool) var debug_show_position = false
export (PackedScene) var weapon
export(PackedScene) var armor
export (PackedScene) var tractor

var weapon_instance
var armor_instance
var tractor_instance

var direction := Vector2()
var velocity := Vector2()

func is_within(v, w, e):
	return v >= w - e and v <= w + e

func _ready():
	$AnimationPlayer.play("idle")
	
	if weapon:
		var _w = weapon.instance()
		$Center/WeaponPort.add_child(_w)
		weapon_instance = _w
	
	if armor:
		var _a = armor.instance()
		$Center/ArmorPort.add_child(_a)
		armor_instance = _a
		
	if tractor:
		var _t = tractor.instance()
		$Center/TractorPort.add_child(_t)
		tractor_instance = _t
	
func _physics_process(dt):
	proc_move(dt)
	if can_rotate:
		 proc_sprite()

func proc_move(dt: float):
	if tractor_instance:
		direction = direction.normalized()
		if velocity.length() > 0:
			tractor_instance.rotation = lerp(tractor_instance.rotation, direction.angle() + PI/2, 0.3)
		velocity = direction * tractor_instance.speed 
		velocity = move_and_slide(velocity)
	
func set_move_target(dest: Vector2):
	$AI.request_path(dest)
	
func proc_sprite():
	if velocity.length() != 0:
		$Center.rotation = direction.angle()
	if debug_show_position:
		$Label.text = String(position)
	
func get_sprite() -> AtlasTexture:
	var tex := AtlasTexture.new()
	tex.atlas = $Center/Sprite.texture
	tex.region = Rect2(0, 0, 8, 8)
	return tex

func touched(bullet : Bullet):
	#armor_instance.health -= bullet.penetration
	pass

func _on_AI_order_done():
	position = position.snapped(Vector2(8, 8))
